﻿using System;
using System.Linq;
using Core.DataAccess.Model;
using Core.DataAccess.Model.Projects;
using Core.Framework.Redis.Queue_Helper;
using Core.IBusiness.IProjectModule;
using Core.Framework.Util;

namespace Core.Business.ProjectModule
{
    public class Project: IProject
    {

        public ProjectList GetProjectInfo(int userKey, string projectToken)
        {
            using (var context = new ProjectContext())
            {

                return context
                    .ProjectList
                    .Where(a => a.UserKey == userKey && a.Token == projectToken)
                    .FirstOrDefault();
            };
        }

        public Tuple<ProjectList, bool> IsExist(int userKey, string userToken, string projectToken)
        {
            var value =
                (string)RedisQueueHelper
                    .HashGet(RedisQueueHelperParameter.ProjectInfoByUserToken, userToken+ projectToken);

            if (!string.IsNullOrWhiteSpace(value))
                return new Tuple<ProjectList, bool>(value.TryToEntity<ProjectList>(),true);

            var info = this.GetProjectInfo(userKey,projectToken);

            if (info == null && info.Id > 0)
                return new Tuple<ProjectList, bool>(null,false);

            RedisQueueHelper
                .HashSet(
                    RedisQueueHelperParameter.ProjectInfoByUserToken,
                    userToken+projectToken,
                    info.TryToJson()
                );

            return new Tuple<ProjectList, bool>(info,false);

        }
    }
}
